import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { User } from './user.entity'
import { UserType } from './type'
import { Response } from '../common/Response'

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
    ){}

    async getOnlineUser(): Promise<User[]> {
        try {
            const users = await this.userRepository.find({ isOnline: 2 })
            console.log(users);
            return users
        } catch (error) {
            throw error
        }
    }

    // 更新用户信息
    async updateUser(props:UserType):Promise<void>{
        try {
            const user: User = await this.userRepository.findOne(props.id)
            await this.userRepository.save({
                ...user[0],
                ...props
            })
        } catch (error) {
            throw error
        }
    }

    // 查找用户
    async findUserById(id:number){
        try {
            const user: User = await this.userRepository.findOne(id)
            return user
        } catch (error) {
            throw error
        }
    }
    
    async addUser(user: User): Promise<Response<any>> {
        try {
            const exsitUser = await this.userRepository.find({ userName: user.userName })            
            if(!exsitUser[0]){
                throw '用户名不存在'
            }
            // const res = await this.userRepository.save(user)
            // console.log(res);
            return {
                code: 0,
                status: 'ok',
                data:{
                    id: exsitUser[0].id
                }
            }
        } catch (error) {
            console.log(error);
            
            return {
                code: -1,
                status: 'error',
                msg: typeof error === 'string' ? error : '添加失败'
            }
        }
    }
}